from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from datetime import datetime
class Department(models.Model):
    """部门模型"""
    name = models.CharField('部门名称', max_length=100, unique=True)
    
    class Meta:
        verbose_name = '部门'
        verbose_name_plural = '部门管理'
    
    def __str__(self):
        return self.name

class Contact(models.Model):
    """通讯录联系人模型"""
    department = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        verbose_name='所属部门'
    )
    is_displayed = models.BooleanField('状态', default=True)
    name = models.CharField('姓名', max_length=50)
    position = models.CharField('职位', max_length=100, blank=True)  # 修改这行，添加blank=True
    phone = models.CharField('电话号码', max_length=20)
    short_code = models.CharField('短号', max_length=10, blank=True)
    order = models.PositiveIntegerField('排序', default=0)  # 新增排序字段
    
    # 新增性别字段，使用选择框限制可选值
    GENDER_CHOICES = (
        ('U', '未知'),
        ('M', '男'),
        ('F', '女'),
    )
    gender = models.CharField('性别', max_length=1, choices=GENDER_CHOICES, default='U')

    # 新增参加工作时间字段
    hire_date = models.DateField('参加工作时间', blank=True, null=True)

    # 新增头像字段
    def get_avatar_upload_path(instance, filename):
        now = datetime.now()
        return f'avatars/{now.year}/{now.month}/{now.day}/{filename}'
    avatar = models.ImageField('头像', upload_to=get_avatar_upload_path, blank=True, null=True)   
    # 新增默认头像
    @property
    def avatar_url(self):
        if self.avatar:
            return self.avatar.url
        else:
            return 'http://192.168.64.166/static/default_avatar.png'

    def __str__(self):
        return str(self.avatar.name)  # 显式转换为字符串

    class Meta:
        verbose_name = '联系人' # 后台右上显示
        verbose_name_plural = '联系人管理'  # 后台左菜单列表中文显示
        ordering = ['order', 'department', 'name']  # 修改排序规则
        indexes = [
            models.Index(fields=['name']),
            models.Index(fields=['department']),
            models.Index(fields=['is_displayed']),
        ]
    
    def __str__(self):
        return self.name

    @property
    def department_name(self):
        return self.department.name
